from sqlalchemy.orm import Session
from core.response import resp_500
from core.logger import logger

from app.audit.models.audit_api_record import AuditApiRecord

class AuditApiRecordHandler():
    """  AuditApiRecord Handler
    """
    def __init__(self):
        pass


    def get_audit_api_record_search(self, db: Session, page: int, per_page: int, field: str, value: str):
        """
        api访问记录表, 根据表字段-模糊查询, 获取api访问记录
        """
        try:
            field_info = {field: value}
            order_info = {"create_time": "desc"}
            result = AuditApiRecord.filter_by_field_search(db, page, per_page, field_info, order_info)
            if not result:
                logger.error(f"get audit api record search, result is null => {field}:{value}")
                return False

        except Exception as e:
            message = f"get audit api record search by {field}:{value} error"
            logger.exception(f"{message} => {e}")
            return resp_500(message)

        return result



    def get_audit_api_record_match(self, db: Session, page: int, per_page: int, field: str, value: str):
        try:
            result = AuditApiRecord.filter_by_field_match(db, page, per_page,{field: value})
            if not result:
                logger.warning(f"get audit api record match failed, result is null => {field}:{value}")
                return False

        except Exception as e:
            message = f"get audit api record match by {field}:{value} error"
            logger.exception(f"{message} => {e}")
            return resp_500(message)

        return result



    def delete_audit_api_record(self, db: Session, data: dict):
        """
        删除api访问记录
        """
        try:
            audit_api_object = AuditApiRecord.get_object_by_uuid(db, data['uuid'])
            if not audit_api_object:
                # 如果不存在， 则异常返回
                logger.error(f"delete audit api record failed, uuid:{data['uuid']} not exist")
                return False

            # 删除api访问记录
            AuditApiRecord.delete_object_by_uuid(db, data['uuid'])
        except Exception as e:
            message = f"delete audit api record error"
            logger.exception(f"{message} data:{data} => {e}")
            return resp_500(message)

        return True




    def add_audit_api_record(self, db: Session, data: dict):
        """
        增加api访问记录
        """
        try:
            # 添加到数据库
            result = AuditApiRecord.add(db, data)
            if not result:
                logger.error(f"add audit api record to database failed")
                return False
        except Exception as e:
            message = f"add audit api record error"
            logger.exception(f"{message} data:{data} => {e}")
            return False

        return True

